package com.red.wine.ui;

import java.io.IOException;
import java.util.List;

import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.wine.R;
import com.red.wine.WineApp;
import com.red.wine.adapter.CityAdapter;
import com.red.wine.model.CityData;
import com.red.wine.model.CityListInfo;
import com.red.wine.model.CityRequest;
import com.red.wine.model.CityReturn;
import com.red.wine.model.Headers;
import com.red.wine.model.RegetPassData;
import com.red.wine.model.RegetPassReq;
import com.red.wine.model.RegisterReturn;
import com.red.wine.sql.CitySqlHelper;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CityActivity extends BaseActivity{
	private ImageView back;
	private EditText searchEdit;
	private ImageView searchImg;
	private ListView listview;
	private Context context;
	private ListView choiceList;
	private String py[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
			"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
			"x", "y", "z" };
	private CitySqlHelper citySqlHelper;
//	private String isfromPur = "";
//	private Bundle bundle;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_layout);
		context = this;
//		bundle = getIntent().getExtras();
//		if(bundle != null){
//			isfromPur = bundle.getString("fromPur");
//		}
		citySqlHelper = new CitySqlHelper();
		citySqlHelper.open(WineApp.getInstance().getSqlHelper());
		back = (ImageView) findViewById(R.id.cityback);
		searchEdit = (EditText) findViewById(R.id.city_serch_edit);
		searchImg = (ImageView) findViewById(R.id.city_search_btn);
		listview = (ListView) findViewById(R.id.city_list);
		choiceList = (ListView) findViewById(R.id.city_choice_listview);
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,R.layout.ccity_choice_item,py);
		choiceList.setDivider(null);
		listview.setCacheColorHint(Color.TRANSPARENT);
		choiceList.setAdapter(adapter1);
		choiceList.setCacheColorHint(Color.TRANSPARENT);
		getData();
		
		back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(!StringUtil.isEmptyOrNull(PrefsUtils.getFrom())){
					if(PrefsUtils.getFrom().equals("1")){
						IntentUtil.redirectToNext(context, PurchActivity.class);
					}else if(PrefsUtils.getFrom().equals("2")){
						IntentUtil.redirectToNext(context, PerInfoActivity.class);
					}
				}
				finish();
			}
		});
		 
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				CityListInfo info = (CityListInfo) adapter.getItem(position);
				PrefsUtils.setCityName(info.getName()+":" + info.getId());
				if(!StringUtil.isEmptyOrNull(PrefsUtils.getFrom())){
					if(PrefsUtils.getFrom().equals("1")){
						IntentUtil.redirectToNext(context, PurchActivity.class);
					}else if(PrefsUtils.getFrom().equals("2")){
						IntentUtil.redirectToNext(context, PerInfoActivity.class);
					}
				}
				finish();
			}
		});
		
		searchImg.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				String key = searchEdit.getText().toString().trim();
				if(!StringUtil.isEmptyOrNull(key)){
					getDataByKey(key);
				}
			}
		});
		choiceList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int index = arg2;
				String key = py[index];
				Log.e("TAG", "key: = " + key);
				if(!StringUtil.isEmptyOrNull(key)){
					getDataByKey(key);
				}
			}
		});
	}
	
	private void getDataByKey(String keyword){
		int numInSQL = citySqlHelper.getCount();
		if(numInSQL > 0){
			datasource = citySqlHelper.getClientInfo(0, numInSQL, keyword);
			adapter.refresh(datasource);
		}else{
			Toast.makeText(context, "暂无城市！", Toast.LENGTH_LONG).show();
		}
	}
	private void getData(){
		showLoading();
		new ServiceAsynTask<CityReturn>() {

			@Override
			protected CityReturn callService() throws IOException,
					JsonParseException, AssertionError {
				CityRequest taste = new CityRequest();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii)");

				CityData data = new CityData();
				data.setLat("121.22");
				data.setLon("2222.s");
				
				
				taste.cmd = "node_city";
				taste.headers = header;
				taste.data = data;
				taste.sid= "7b8bb3e0152c9ed086f287ac37b927aa9085f2";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();

				return ServiceHelper.getInstance().postData(urlstr, send,
						CityReturn.class);
			}

			@Override
			protected void runWithResult(CityReturn result) throws Exception {
				
				if (result != null) {
					bindData(result);
					Log.e("TAG", "isnotnull");
				} else {
					Toast.makeText(context, "获取城市列表失败", Toast.LENGTH_SHORT).show();
				}
				hideLoading();
			}

			@Override
			protected void runWithError(CityReturn result, int iErrorCode)
					throws Exception {
				Log.e("TAG", "异常");
				finish();
				hideLoading();
			}
		}.execute();
	}
	
	private List<CityListInfo> datasource;
	private CityAdapter adapter = null;
	private void bindData(CityReturn result){
		if(result.getRsp().equals("1")){
			if(result.getData() != null){
				if(citySqlHelper.getCount() > 0){
					citySqlHelper.delete();
				}
				
				datasource = result.getData().getItems();
				if(datasource != null && datasource.size() > 0){
					if(adapter == null){
						adapter = new CityAdapter(context, datasource);
					}
					if(adapter != null){
						try{
							for (int i = 0; i < datasource.size(); i++) {
								citySqlHelper.addClientInfo(datasource.get(i));
							}
						}catch (Exception e) {
							e.printStackTrace();
						}
						listview.setAdapter(adapter);
					}
				}
			}
		}else{
			Toast.makeText(context, "获取城市列表失败", Toast.LENGTH_SHORT).show();
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(!StringUtil.isEmptyOrNull(PrefsUtils.getFrom())){
				if(PrefsUtils.getFrom().equals("1")){
					IntentUtil.redirectToNext(context, PurchActivity.class);
				}else if(PrefsUtils.getFrom().equals("2")){
					IntentUtil.redirectToNext(context, PerInfoActivity.class);
				}
			}
			finish();
		}
			
		return super.onKeyDown(keyCode, event);
	}
	
}
